﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using ToolHelp.Model;

namespace ToolHelp
{
    public static class DataTableHelper
    {
        /// <summary>
        /// 根据注解返回固定的DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByList<T>(List<T> list)
        {
            DataTable dataTable2 = new DataTable();
            Dictionary<string, string> fields = new Dictionary<string, string>();
            var property = list[0].GetType().GetProperties();
            var indexProperty = 0;
            foreach (var item in property)
            {
                var typeName = item.PropertyType.Name;
                if (item.CustomAttributes.Any(f => f.AttributeType == typeof(ExportNamesAttribute)))
                {
                    var attrName = ((ExportNamesAttribute)(item.GetCustomAttributes(typeof(ExportNamesAttribute), false).FirstOrDefault())).TestName;
                    System.Diagnostics.Debug.WriteLine(attrName);
                    dataTable2.Columns.Add(attrName);
                };
                indexProperty++;
            }

            foreach (var item in list)
            {
                var dataRow = dataTable2.NewRow();
                var lieIndex = 0;
                foreach (var item2 in property)
                {
                    if (item2.CustomAttributes.Any(f => f.AttributeType == typeof(ExportNamesAttribute)))
                    {
                        var attrName = ((ExportNamesAttribute)(item2.GetCustomAttributes(typeof(ExportNamesAttribute), false).FirstOrDefault())).TestName;
                        dataRow[lieIndex] = item2.GetValue(item);
                        lieIndex++;
                    };
                }
                dataTable2.Rows.Add(dataRow);
            }
            return dataTable2;
        }
    }
}
